import { In } from "typeorm";
import { dataSource } from "../../db/typeorm";
import {
  ArticleCategory,
  ArticleCategoryRole,
  ArticleRoleCategoryModel,
} from "../../entity/article_category";
import { getUserRoleByUserId } from "../user/user";
import { CreateCategory } from "./type";
import { checkIsRepeat, listToTree } from "./utils";

// 根据获取文章分类树
// 只能查询当前用户创建的或者关联的角色权限的分类
export async function getArticleCategoryTree(user_id: number) {
  const roleIds: number[] = await getUserRoleByUserId(user_id);
  const categorys = await dataSource
    .getRepository(ArticleCategory)
    .createQueryBuilder("article_category")
    .leftJoinAndSelect(
      "article_category.articleCategoryRoles",
      "articlecategory_role",
    )
    .where("articlecategory_role.role_id in (:...roleIds)", { roleIds })
    .orWhere("article_category.create_user = :user_id", { user_id })
    .getMany();

  return listToTree(categorys, 0);
}

// 更新文章分类信息
// 创建者和拥有该分类角色权限的均有操作权限
export async function articleCategoryUpdate(body: any, user_id: string) {
  if (!body.category_id) {
    throw new Error("分类ID不能为空！");
  }
  const role_id = body.role_id;

  delete body.role_id;

  // 校验该分类当前用户是否有更改权限
  const roles = await getUserRoleByUserId(Number(user_id));

  // 查询分类角色中间表
  const roleCategorysResult = await dataSource
    .getRepository(ArticleCategory)
    .findOne({
      relations: ["articleCategoryRoles"],
      where: { category_id: body.category_id },
    });

  // 判断该分类当前用户是否有操作权限
  if (roleCategorysResult) {
    if (
      Number(user_id) === roleCategorysResult?.create_user ||
      checkIsRepeat(roleCategorysResult.articleCategoryRoles, roles)
    ) {
      // 更新中间表(删除、新增)
      if (role_id) {
        await dataSource
          .getRepository(ArticleCategoryRole)
          .createQueryBuilder()
          .delete()
          .where("category_id = :category_id", {
            category_id: body.category_id,
          })
          .execute();

        await dataSource.getRepository(ArticleCategoryRole).save(
          role_id.split(",").map((item: ArticleCategory) => ({
            role_id: item,
            category_id: body.category_id,
          })),
        );
      }

      // 开始更新分类
      await dataSource
        .createQueryBuilder()
        .update(ArticleCategory)
        .set(body)
        .where("category_id = :id", { id: body.category_id })
        .execute();
      return null;
    }
  }

  throw new Error("无权操作该分类！");
}

// 添加文章分类
export async function articleCategoryCreate(body: CreateCategory) {
  await dataSource.transaction(async (transactionalEntityManager) => {
    const result = await transactionalEntityManager
      .getRepository(ArticleCategory)
      .insert(body);

    // 更新中间表
    if (result && result.raw.insertId && body.role_id) {
      let role_ids = body.role_id.split(",");
      let insertDatas = role_ids.map((item) => ({
        role_id: item,
        category_id: result.raw.insertId,
      }));
      await transactionalEntityManager
        .getRepository(ArticleRoleCategoryModel)
        .insert(insertDatas);
    }
  });
}
